from rest_framework import serializers
from rest_framework.views import  APIView
from rest_framework.response import Response
from rest_framework import status
from api.utils.auth import UserAuthentication
from api import models

class NewsFavorModelSerializer(serializers.ModelSerializer):
    class Meta:
        model=models.NewsFavorRecord
        fields=['news',]

class NewsFavor(APIView):

    authentication_classes = [UserAuthentication,]

    def post(self,request,*args,**kwargs):
            ser=NewsFavorModelSerializer(data=request.data)
            if not ser.is_valid():
                return Response({},status=status.HTTP_400_BAD_REQUEST)
            news_obj=ser.validated_data.get('news')
            queryset = models.NewsFavorRecord.objects.filter(news=news_obj)
            if queryset.exists():
                queryset.delete()
                return Response({}, status=status.HTTP_200_OK)
            else:
                models.NewsFavorRecord.objects.create(user=request.user,news=news_obj)
                return Response({}, status=status.HTTP_201_CREATED)